import os
import shutil

# 源文件夹和目标文件夹是同一个路径
base_folder = '/Users/aresen/Downloads/工信部/文件发布/附件'

# 每批最大文件数
batch_size = 200

# 获取所有文件列表（只取文件，排除子目录）
files = [f for f in os.listdir(base_folder) if os.path.isfile(os.path.join(base_folder, f))]

total_files = len(files)
count = 0

print(f"总共找到 {total_files} 个文件，开始按每批最多 {batch_size} 个进行复制...\n")

while count < total_files:
    # 计算当前批次最多能取多少文件
    remaining = total_files - count
    current_batch_count = min(batch_size, remaining)

    # 当前批次要复制的文件范围
    current_batch_files = files[count:count + current_batch_count]

    # 新目录名称：已复制的数量 + 当前批次数量
    folder_name = str(count + current_batch_count)
    new_folder_path = os.path.join(base_folder, folder_name)

    # 如果目录已存在，自动加上后缀防止冲突（可选）
    original_folder_name = folder_name
    suffix = 1
    while os.path.exists(new_folder_path):
        new_folder_path = os.path.join(base_folder, f"{original_folder_name}_{suffix}")
        suffix += 1

    os.makedirs(new_folder_path)
    print(f"✅ 已创建目录：{new_folder_path}")

    # 复制文件
    for file in current_batch_files:
        src = os.path.join(base_folder, file)
        dst = os.path.join(new_folder_path, file)

        if os.path.exists(dst):
            print(f"⚠️ 跳过：{file}（已存在）")
            continue

        try:
            shutil.copy2(src, dst)  # 保留元数据
            print(f"📄 成功复制：{file}")
        except Exception as e:
            print(f"❌ 无法复制 {file}: {e}")

    count += current_batch_count
    print(f"📦 本批共复制 {current_batch_count} 个文件，累计已复制 {count} 个。\n")

print("🎉 所有文件复制完成！")
